package scatter.role.rest.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import scatter.common.rest.exception.BusinessDataNotFoundException;
import scatter.role.pojo.form.*;
import scatter.role.rest.RoleConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.RestController;
import scatter.common.rest.controller.BaseAddUpdateQueryFormController;
import scatter.role.pojo.po.RoleUserRel;
import scatter.role.pojo.vo.RoleUserRelVo;
import scatter.role.rest.service.IRoleUserRelService;

import javax.validation.Valid;
/**
 * <p>
 * 角色用户关系表 前端控制器
 * </p>
 *
 * @author yw
 * @since 2020-12-11
 */
@Api(tags = "角色用户关系相关接口")
@RestController
@RequestMapping(RoleConfiguration.CONTROLLER_BASE_PATH + "/role-user-rel")
public class RoleUserRelController extends BaseAddUpdateQueryFormController<RoleUserRel, RoleUserRelVo, RoleUserRelAddForm, RoleUserRelUpdateForm, RoleUserRelPageQueryForm> {


    @Autowired
    private IRoleUserRelService iRoleUserRelService;

     @Override
	 @ApiOperation("添加角色用户关系")
     @PreAuthorize("hasAuthority('RoleUserRel:add')")
     @PostMapping
     @ResponseStatus(HttpStatus.CREATED)
     public RoleUserRelVo add(@RequestBody @Valid RoleUserRelAddForm addForm) {
         return super.add(addForm);
     }

     @Override
	 @ApiOperation("根据ID查询角色用户关系")
     @PreAuthorize("hasAuthority('RoleUserRel:queryById')")
     @GetMapping("/{id}")
     @ResponseStatus(HttpStatus.OK)
     public RoleUserRelVo queryById(@PathVariable String id) {
         return super.queryById(id);
     }

     @Override
	 @ApiOperation("根据ID删除角色用户关系")
     @PreAuthorize("hasAuthority('RoleUserRel:deleteById')")
     @DeleteMapping("/{id}")
     @ResponseStatus(HttpStatus.NO_CONTENT)
     public boolean deleteById(@PathVariable String id) {
         return super.deleteById(id);
     }

     @Override
	 @ApiOperation("根据ID更新角色用户关系")
     @PreAuthorize("hasAuthority('RoleUserRel:update')")
     @PutMapping
     @ResponseStatus(HttpStatus.CREATED)
     public RoleUserRelVo update(@RequestBody @Valid RoleUserRelUpdateForm updateForm) {
         return super.update(updateForm);
     }

    @Override
	@ApiOperation("不分页查询角色用户关系")
    @PreAuthorize("hasAuthority('RoleUserRel:getList')")
    @GetMapping("/getList")
    @ResponseStatus(HttpStatus.OK)
    public List<RoleUserRelVo> getList(RoleUserRelPageQueryForm listPageForm) {
         return super.getList(listPageForm);
    }

    @Override
	@ApiOperation("分页查询角色用户关系")
    @PreAuthorize("hasAuthority('RoleUserRel:getPage')")
    @GetMapping("/getPage")
    @ResponseStatus(HttpStatus.OK)
    public IPage<RoleUserRelVo> getPage(RoleUserRelPageQueryForm listPageForm) {
         return super.getPage(listPageForm);
    }



    @ApiOperation("用户分配角色")
    @PreAuthorize("hasAuthority('roleUser:single:userAssignRole')")
    @PostMapping("/user/assign/role")
    @ResponseStatus(HttpStatus.CREATED)
    public Boolean userAssignRole(@RequestBody @Valid UserAssignRoleForm cf) {
        return iRoleUserRelService.removeAndAssignRel(cf.getUserId(),cf.getCheckedRoleIds(),cf.getUncheckedRoleIds(),cf.getIsLazyLoad(), RoleUserRel::getUserId,RoleUserRel::getRoleId,(relDto)->new RoleUserRel().setUserId(relDto.getMainId()).setRoleId(relDto.getOtherId()));
    }

    @ApiOperation("根据用户ID查询已分配的角色id")
    @PreAuthorize("hasAuthority('roleUser:single:queryByUserId')")
    @GetMapping("/user/{userId}")
    @ResponseStatus(HttpStatus.OK)
    public List<String> queryByUserId(@PathVariable String userId) {
        List<RoleUserRel> rels = iRoleUserRelService.getByUserId(userId);
        if (isEmpty(rels)) {
            throw new BusinessDataNotFoundException("数据不存在");
        }

        return rels.stream().map(item -> item.getRoleId()).collect(Collectors.toList());
    }

    @ApiOperation("清空用户下的所有角色")
    @PreAuthorize("hasAuthority('roleUser:single:deleteByUserId')")
    @DeleteMapping("/user/{userId}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public Boolean deleteByUserId(@PathVariable String userId) {
        return iRoleUserRelService.removeAssignRel(userId,RoleUserRel::getUserId);
    }


    @ApiOperation("角色分配用户")
    @PreAuthorize("hasAuthority('roleUser:single:roleAssignUser')")
    @PostMapping("/role/assign/user")
    @ResponseStatus(HttpStatus.CREATED)
    public Boolean roleAssignUser(@RequestBody @Valid RoleAssignUserForm cf) {
        return iRoleUserRelService.removeAndAssignRel(cf.getRoleId(),cf.getCheckedUserIds(),cf.getUncheckedUserIds(),cf.getIsLazyLoad(), RoleUserRel::getRoleId,RoleUserRel::getUserId,(relDto)->new RoleUserRel().setRoleId(relDto.getMainId()).setUserId(relDto.getOtherId()));
    }

    @ApiOperation("根据角色id查询已分配的用户id")
    @PreAuthorize("hasAuthority('roleUser:single:queryByRoleId')")
    @GetMapping("/role/{roleId}")
    @ResponseStatus(HttpStatus.OK)
    public List<String> queryByRoleId(@PathVariable String roleId) {
        List<RoleUserRel> rels = iRoleUserRelService.getByRoleId(roleId);
        if (isEmpty(rels)) {
            throw new BusinessDataNotFoundException("数据不存在");
        }
        return rels.stream().map(item -> item.getUserId()).collect(Collectors.toList());
    }

    @ApiOperation("清空角色下的所有用户")
    @PreAuthorize("hasAuthority('roleUser:single:deleteByRoleId')")
    @DeleteMapping("/role/{roleId}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public Boolean deleteByRoleId(@PathVariable String roleId) {
        return iRoleUserRelService.removeAssignRel(roleId,RoleUserRel::getRoleId);
    }
}
